package com.qidian.buy.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
 * Author: 戴着假发的程序员
 * Date: 2023-07-06 10:12
 * company: 起点编程
 * Description:
 **/

public class Tools {
    // 获取当前系统时间的字符串格式
    public static String now(String pattern){
        pattern = pattern==null?"yyyy-MM-dd HH:mm:ss":pattern;
        return new SimpleDateFormat(pattern).format(new Date());
    }

    public static String dateFormat(Date date,String pattern){
        pattern = pattern==null?"yyyy-MM-dd HH:mm:ss":pattern;
        return new SimpleDateFormat(pattern).format(date);
    }



    /**
     * 对象转换为json
     * @param obj
     * @return
     */
    public static String object2json(Object obj){
        try {
            return new ObjectMapper().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json转换为对象
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T json2object(String json,Class<T> clazz){
        try {
            return new ObjectMapper().readValue(json,clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * JSON转换为集合
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> json2list(String json, Class<T> clazz){
        try {
            return new ObjectMapper().readValue(json, new TypeReference<List<T>>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
